<?php
declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Http\Api;
use Hyperf\Server\ServerFactory;
use Hyperf\Redis\RedisFactory;
use Hyperf\Utils\ApplicationContext;
use App\Model\User;
class Push extends \App\Controller\Http\Base
{
    // 全站推送消息
    // {"data":{"msg":{"msg":"测试","uid":"12345"}},"token":"123456"}
    public function all()
    {
        $params = $this->request->all();
        $data=$params['data'];
        $count=0;
        if (isset($data['msg'])) {
            $msg=$data['msg'];
            $container = ApplicationContext::getContainer();
            // 给websocket 客户端推送消息
            $server=$container->get(ServerFactory::class)->getServer()->getServer();
            $onlineFdList=[];
            $fdList=$server->connections;
            foreach ($server->connections as $fd) {
                $fd=intval($fd);
                // 需要先判断是否是正确的websocket连接，否则有可能会push失败
                if ($server->isEstablished($fd)) {
                    $count++;
                    $server->push($fd, json_encode($msg,JSON_UNESCAPED_UNICODE));
                    // $onlineFdList[]=$fd;
                }else{
                	// $redis = $container->get(RedisFactory::class)->get('wsUid');
                        //移除集合中指定的fd
                    // $redis->sRem($uid, $fd);
                }
            }
            return ['code'=>0,'result'=>['count'=>$count],'message'=>'ok'];
        }else{
            return ['code'=>1,'fail'=>'数据格式有误'];
        }
    }
    // 指定uid推送，支持群发
    // {"data":{"msg":{"msg":"测试","uid":"12345"},"uids":["123456"]},"token":"令牌"}
    public function uids()
    {
        $params = $this->request->all();
        $data=$params['data'];
        $count=0;
        if (isset($data['msg']) && isset($data['uids']) && is_array($data['uids'])) {
            $msg=$data['msg'];
            $uids=$data['uids'];
            $container= ApplicationContext::getContainer();
            $redis = $container->get(RedisFactory::class)->get('wsUid');

            $server=$container->get(ServerFactory::class)->getServer()->getServer();

            
             foreach ($uids as $k => $uid) {
                if (is_int($uid)) {
                   $uid=''.$uid;
                }
                $fdList=$redis->smembers($uid)??[];

                 foreach ($fdList as $key => $fd) {
                    $fd=intval($fd);
                    if ($server->isEstablished($fd)) {
                        $count++;
                        $server->push($fd, json_encode($msg,JSON_UNESCAPED_UNICODE));
                        // $onlineFdList[$uid]=$fd;
                    }else{
                        //移除集合中指定的fd
                       $redis->sRem($uid, $fd);
                    }
                 }
                
             }
           }else{
                return ['code'=>1,'fail'=>'数据格式有误'];
           }
        return ['code'=>0,'result'=>['count'=>$count],'message'=>'ok'];
    }
    // 集合推送，不同uid推送不同信息
    // {token:'令牌验证',data:{list:[{uid:'uid1','msg':'推送内容'}]}}
    public function list()
    {
            $params = $this->request->all();
            $data=$params['data'];
            $count=0;
        if (isset($data['list']) &&  is_array($data['list'])) {
            $list=$data['list'];
            $container= ApplicationContext::getContainer();
            $redis = $container->get(RedisFactory::class)->get('wsUid');
            // var_dump($redis->keys("*"));
            $server=$container->get(ServerFactory::class)->getServer()->getServer();

            foreach ($list as $k => $item) {
               if (isset($item['msg']) && isset($item['uid'])) {
                $uid=$item['uid'];
                if (is_int($uid)) {
                   $uid=''.$uid;
                }
 
                $fdList=$redis->smembers($uid);
                 foreach ($fdList as $key => $fd) {
                    $fd=intval($fd);
                    // var_dump("fd:".$fd."：在线：".$server->isEstablished($fd));
                    if ($server->isEstablished($fd)) {
                        $count++;
                        $server->push($fd, json_encode($item['msg'],JSON_UNESCAPED_UNICODE));
                        // $onlineFdList[$uid]=$fd;
                    }else{
                        //移除集合中指定的fd
                       $redis->sRem($uid, $fd);
                    }
                 }

               }
            }
           }else{
                return ['code'=>1,'fail'=>'数据格式有误'];
           }
        return ['code'=>0,'result'=>['count'=>$count],'message'=>'ok'];
    }
}